#ifndef SHA256_H
#define SHA256_H

#include <vector>
#include <cstdint>
#include <cstring>
#include <string>
#include <sstream>
#include <iomanip>

namespace TSBLib {

    class SHA256 {
    public:
        SHA256();
        void update(const void* data, size_t len);
        std::string final();

    private:
        typedef uint32_t WORD; // 定义 WORD 为 32 位无符号整数
        typedef unsigned char BYTE; // 定义 BYTE 为 8 位字节

        static const size_t SHA256_BLOCK_SIZE = 32; // SHA256 输出为 32 字节

        struct SHA256_CTX {
            BYTE data[64];
            WORD datalen;
            unsigned long long bitlen;
            WORD state[8];
        };

        SHA256_CTX ctx;

        void sha256_transform(const BYTE data[]);
        void sha256_init();
        void sha256_final(BYTE hash[]);

        // 内联辅助函数，替代宏定义
        inline WORD ROTLEFT(WORD a, WORD b) {
            return ((a << b) | (a >> (32 - b)));
        }

        inline WORD ROTRIGHT(WORD a, WORD b) {
            return ((a >> b) | (a << (32 - b)));
        }

        inline WORD CH(WORD x, WORD y, WORD z) {
            return (x & y) ^ (~x & z);
        }

        inline WORD MAJ(WORD x, WORD y, WORD z) {
            return (x & y) ^ (x & z) ^ (y & z);
        }

        inline WORD EP0(WORD x) {
            return ROTRIGHT(x, 2) ^ ROTRIGHT(x, 13) ^ ROTRIGHT(x, 22);
        }

        inline WORD EP1(WORD x) {
            return ROTRIGHT(x, 6) ^ ROTRIGHT(x, 11) ^ ROTRIGHT(x, 25);
        }

        inline WORD SIG0(WORD x) {
            return ROTRIGHT(x, 7) ^ ROTRIGHT(x, 18) ^ (x >> 3);
        }

        inline WORD SIG1(WORD x) {
            return ROTRIGHT(x, 17) ^ ROTRIGHT(x, 19) ^ (x >> 10);
        }

        static const WORD k[64];
    };

}

#endif // SHA256_H
